/*
 * @Author: yxfan
 * @Date: 2024-06-04 19:29:13
 * @LastEditTime: 2024-06-04 20:18:05
 * @FilePath: /umi-demo/src/pages/demo/KeepAlive/KeepAliveFn.jsx
 * @Description: 简单的KeepAlive
 */

import React, {
    Component,
    createContext,
    useCallback,
    useMemo,
    useState,
    useRef,
    Children,
    useContext,
    useLayoutEffect,
    useEffect,
} from 'react';

const Context = createContext();

export function AliveScope(props) {
    const [state, setState] = useState({});
    const nodes = useRef({});

    const keep = useCallback((id, children) => {
        return new Promise((resolve) => {
            setState((state) => ({ ...state, [id]: { id, children } }));
            Promise.resolve().then(() => {
                // debugger
                resolve(nodes.current[id]);
            });
        });
    });

    return (
        <Context.Provider value={keep}>
            {props.children}
            {Object.values(state).map(({ id, children }) => (
                <div
                    key={id}
                    ref={(node) => {
                        nodes.current[id] = node;
                    }}
                    className="keep-alive-node"
                >
                    {children}
                </div>
            ))}
        </Context.Provider>
    );
}

export default function KeepAlive(props) {
    const { id, children } = props;
    const keep = useContext(Context);

    const container = useRef();

    useEffect(() => {
        keep(id, children).then((node) => {
            container.current.appendChild(node);
        });
    }, []);

    return <div className="keep-alive-container" ref={container}></div>;
}
